package com.atguigu.guli.service.oss.controller.admin;

import com.atguigu.guli.service.base.exception.GuLiException;
import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Api("阿里云文件管理-后台")
@RequestMapping("/admin/oss/file")
@CrossOrigin//跨域
@RestController
@Slf4j
public class FileController {

    @Autowired
    FileService fileService;

    @ApiOperation("测试上传")
    @PostMapping("testOss")
    public R testOss(
            @ApiParam(value = "上传图片", required = true)
            @RequestParam("file") MultipartFile file,

            @ApiParam(value = "模块", required = true)
            @RequestParam String module
    ) {

        try {
            String originalFilename = file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            String url = fileService.upload(inputStream, module, originalFilename);
            return R.ok().message("文件上传成功").data("url", url);
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
            throw new GuLiException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }

    }
}

